package config

import (
	"fmt"

	"gddgame.cc/galaxy/common/dsl/game"
)

const providerName = "config"

func init() {
	_ = game.RegisterGlobalModule(game.ModuleProvider{
		Name: providerName,

		OnInit: func(env *game.Environment) error {
			var err error
			if _, err = env.RegisterModel(SettingConfigName, &SettingConfig{}); err != nil {
				return err
			}
			return nil
		},
	})
}

func GetConfigData(env *game.Environment, exec func(config *SettingConfig) (interface{}, error)) ([]SettingConfig, error) {
	var configs []SettingConfig
	model, err := env.GetModel(SettingConfigName)
	if err != nil {
		return nil, err
	}
	_, err = model.Query().Where("=", "status", 1).Find(&configs)
	if err != nil {
		return nil, err
	}

	for k := range configs {
		v, err := exec(&configs[k])
		if err != nil {
			return nil, fmt.Errorf("config %s format error:%s", configs[k].Key, err)
		}
		if err := env.SetConfig(configs[k].Key, v); err != nil {
			return nil, fmt.Errorf("config %s store error:%s", configs[k].Key, err)
		}
	}
	return configs, nil
}
